<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\Sms;
use app\common\model\Cargo;
use app\common\model\DriverInfo;
use app\common\model\Order;
use app\common\model\Passenger;
use app\common\model\SubOrder;
use app\common\model\User;
use app\common\model\Withdraw;
use think\facade\Config;
use think\facade\Db;
use think\facade\Validate;

class Driver extends Api
{
    protected $noNeedLogin = [];
    protected $noNeedRight = '*';

    /**
     * 申请成为司机
     */
    public function apply(){
        $user=$this->auth->getUser();

        $data=[
            'user_id'=>$user['id'],
            'name'=>request()->param('name',''),
            'id_no'=>request()->param('id_no',''),
            'mobile'=>request()->param('mobile',''),

            'car_color'=>request()->param('car_color',''),
            'car_model'=>request()->param('car_model',''),
            'car_no'=>request()->param('car_no',''),

            'driver_license_front'=>request()->param('driver_license_front',''),
            'driver_license_back'=>request()->param('driver_license_back',''),
            'car_license_front'=>request()->param('car_license_front',''),
            'car_license_back'=>request()->param('car_license_back',''),
            'car_img_front'=>request()->param('car_img_front',''),
            'car_img_inside'=>request()->param('car_img_inside',''),

            'online_drive_license'=>request()->param('online_drive_license',''),
            'online_transport_license'=>request()->param('online_transport_license',''),
            'status'=>'reviewing',
            'create_time'=>time()
        ];
        $driver=DriverInfo::where(['user_id'=>$user['id']])->find();
        /*if($driver&&$driver['status']=='reviewing'){
            $this->error('司机信息正在审核中，无需再次提交');
        }*/
        if($driver&&$driver['status']=='normal'){
            $this->error('司机信息已通过审核，无需再次提交');
        }
        if($driver&&$driver['status']=='deleted'){
            $this->error('司机信息已被停用，请联系客服处理');
        }

        Db::startTrans();
        try {
            validate('\app\common\validate\DriverInfo')->scene('apply')->check($data);

            if($driver){
                DriverInfo::update($data,['user_id'=>$user['id']]);
            }
            else{
                DriverInfo::insert($data);
            }

            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            // 验证失败 输出错误信息
            $this->error($e->getMessage());
        }
        $this->success('成功');
    }

    /**
     * 司机创建订单
     */
    public function createOrder(){
        $user=$this->auth->getUser();

        $driver_info=DriverInfo::get(['user_id'=>$user['id'],'status'=>'normal'])?:[];
        if(!$driver_info){
            $this->error('非司机，不可使用此功能');
        }

        $order=[
            'driver_id'             =>$user['id'],
            'start_address'         =>request()->param('start_address'),
            'start_lon'             =>request()->param('start_lon'),
            'start_lat'             =>request()->param('start_lat'),
            'end_address'           =>request()->param('end_address'),
            'end_lon'               =>request()->param('end_lon'),
            'end_lat'               =>request()->param('end_lat'),
            'create_by_driver'      =>1,
            'user_id'               =>0,
            'type'                  =>request()->param('type'),
            'order_num'             =>0,
            'total_money'           =>0,
            'total_driver_money'    =>0,
            'total_platform_money'  =>0,
            'has_monopoly'          =>request()->param('type','')=='monopoly'?1:0,
            'has_share'             =>request()->param('type','')=='share'?1:0,
            'has_cargo'             =>request()->param('type','')=='cargo'?1:0,
            'status'                =>2,
            'create_time'           =>time()
        ];

        $start_time_text=request()->param('start_time','');
        $end_time_text=request()->param('end_time','');
        if(!$start_time_text){
            $this->error('请选择出发时间');
        }
        if(!$end_time_text){
            $this->error('请选择结束时间');
        }
        $order['start_time_begin']=$order['start_time_end']=strtotime($start_time_text);
        $order['end_time']=strtotime($end_time_text);
        if($order['end_time']<$order['start_time_begin']){
            $this->error('结束时间不可早于开始时间');
        }

        if(!in_array($order['type'],['monopoly','share','cargo'])){
            $this->error('订单类型错误');
        }


        if(!$order['start_address']){
            $this->error('请选择起点');
        }
        if(!$order['start_lon']||!$order['start_lat']||$order['start_lon']=='undefined'||$order['start_lat']=='undefined'||$order['start_lon']=='null'||$order['start_lat']=='null'){
            $this->error('起点坐标错误');
        }
        if(!$order['end_address']){
            $this->error('请选择终点');
        }
        if(!$order['end_lon']||!$order['end_lat']||$order['end_lon']=='undefined'||$order['end_lat']=='undefined'||$order['end_lon']=='null'||$order['end_lat']=='null'){
            $this->error('终点坐标错误');
        }


        $id=Order::insertGetId($order);

        if($id){
            $this->success('成功',Order::with(['sub_order'])->where(['id'=>$id])->find());
        }
        else{
            $this->error('创建订单出错');
        }
    }

    /**
     * 我发布的行程
     */
    public function order(){
        $user       =$this->auth->getUser();
        $page       =request()->param('page')?:1;
        $status     = $this->request->request('status')?:'all';

        $driver_info=DriverInfo::get(['user_id'=>$user['id'],'status'=>'normal'])?:[];
        if(!$driver_info){
            $this->error('非司机，不可使用此功能');
        }

        if(!in_array($status,['all','accepted','started','arrived','serving','finished','evaluated','canceled','i_create'])){
            $this->error('场景类型参数错误');
        }

        $where=[
            ['driver_id','=',$user['id']],
        ];

        switch ($status){
            case 'accepted':
                $where[]=['status','=',2];
                break;
            case 'started':
                $where[]=['status','=',3];
                break;
            case 'arrived':
                $where[]=['status','=',4];
                break;
            case 'serving':
                $where[]=['status','=',5];
            case 'arrived_end':
                $where[]=['status','=',6];
            case 'finished':
                $where[]=['status','=',7];
                break;
            case 'evaluated':
                $where[]=['driver_comment_time','not null'];
                $where[]=['status','=',8];
                break;
            case 'canceled':
                $where[]=['status','=',10];
                break;
            case 'i_create':
                $where[]=['driver_id','=',$user['id']];
                $where[]=['create_by_driver','=','1'];
                break;
            default:
                break;
        }

        $list=Order::where($where)->page($page,10)->select()?:[];

        foreach ($list as &$l){
            $where=[
                ['parent_id','=',$l['id']],
                ['status','<>',10]
            ];

            $p_orders=SubOrder::where($where)->where('type','in',['monopoly','share'])->column('passenger_id');
            $person=Passenger::where('id','in',$p_orders)->field('sum(adult) as a,sum(child) as c,sum(baby) as b')->find();
            $l['passenger_order_num']=count($p_orders);
            $l['adult']=$person['a']?:0;
            $l['child']=$person['c']?:0;
            $l['baby']=$person['b']?:0;

            $c_orders=SubOrder::where($where)->where('type','in',['cargo'])->column('cargo_id');
            $cargo=Cargo::where('id','in',$c_orders)->select();
            $str='';
            foreach ($cargo as $c){
                $str.=$str==''?'':',';
                $str.=$c['name'].$c['weight'].'kg';
            }
            $l['cargo_order_num']=count($c_orders);
            $l['cargo']=$str;


            $paid=SubOrder::where($where)->where('pay_status','<>','0')->count()?:0;
            $l['paid_num']=$paid;
        }

        $this->success('成功',$list);
    }

    /**
     * 行程中子订单
     */
    public function subOrder(){
        $user=$this->auth->getUser();
        $order_id=request()->param('order_id')?:0;

        $driver_info=DriverInfo::get(['user_id'=>$user['id'],'status'=>'normal'])?:[];
        if(!$driver_info){
            $this->error('非司机，不可使用此功能');
        }

        $list=SubOrder::with(['user','passenger','cargo'])
            ->where(['parent_id'=>$order_id])
            ->select()?:[];

        $this->success('成功',$list);
    }


    /**
     * 获取绑定信息
     */
    public function bindingInfo()
    {
        $user = $this->auth->getUser();
        $data = [
            'wx' => ['wx_account' => $user->wx_account?:'','wx_name' => $user->wx_name?:''],
            'ali' => ['ali_account' => $user->ali_account?:'','ali_name' => $user->ali_name?:''],
        ];
        $this->success('请求成功',$data);
    }

    /**
     * 绑定微信/支付宝
     */
    public function binding()
    {
        $user = $this->auth->getUser();

        $type    = $this->request->request('type');
        $account = $this->request->request('account');
        $name    = $this->request->request('name');

        if (!$type || !in_array($type,['ali','wx'])) {
            $this->error("绑定类型错误");
        }

        if (!$name || !$account) {
            $this->error('绑定数据不能为空');
        }

        if(trim($name)=='null'||trim($account)=='null'){
            $this->error('参数不能为字符串"null"');
        }
        if(trim($name)=='undefined'||trim($account)=='undefined'){
            $this->error('参数不能为字符串"undefined"');
        }

        switch ($type) {
            case 'ali':
                $user->ali_account = $account;
                $user->ali_name    = $name;
                break;
            case 'wx':
                $user->wx_account = $account;
                $user->wx_name    = $name;
                break;
            default:
                break;
        }

        $result = $user->save();
        if ($result) {
            $this->success('绑定成功');
        } else {
            $this->error('绑定失败');
        }
    }

    /**
     * 提现申请
     */
    public function withdraw()
    {
        $user       = $this->auth->getUser();

        $money = $this->request->request('money');
        $type   = $this->request->request('type');

        if (!$money || $money < 0) {
            $this->error("提现金额必须大于0");
        }

        $withdraw_min = Config::get('site.withdraw_min');
        if ($withdraw_min)
            if ($money < $withdraw_min)
                $this->error('最小提现金额: ' . $withdraw_min);

        if (!$type || !in_array($type,['ali','wx']))
            $this->error("提现类型错误");

        if ($money > $user['money'])
            $this->error('余额不足');

        if ($type == 'ali') {
            $paymen_type = '支付宝';
            $account     = $user->ali_account;
            $name        = $user->ali_name;
        }

        if ($type == 'wx') {
            $paymen_type = '微信';
            $account     = $user->wx_account;
            $name        = $user->wx_name;
        }

        if (!$account || !$name)
            $this->error("请先绑定{$paymen_type}提现信息");

        $order_sn    = makePaySn($user['id']);

        $memo = '提现' . $money . '元到' . $paymen_type;
        $data = [
            'user_id'    => $user['id'],
            'money'      => $money,
            'type'       => $type,
            'account'    => $account,
            'name'       => $name,
            'memo'       => $memo,
            'order_sn'   => $order_sn,
            'status'     => 'apply'
        ];

        try {
            $result = Withdraw::create($data);
            User::money($money*-1,$user['id'],$memo);
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }

        if ($result) {
            $this->success('申请成功');
        } else {
            $this->error('申请失败');
        }
    }



    /**
     * 修改联系电话
     */
    public function changemobile()
    {
        $user = $this->auth->getUser();
        $mobile = $this->request->request('mobile');
        $captcha = $this->request->request('captcha');
        if (! $mobile || ! $captcha) {
            $this->error(__('请填写正确的手机号码与验证码'));
        }
        if (! Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('请填写正确的手机号码'));
        }
        $driver=DriverInfo::where(['user_id'=>$user['id']])->find()?:[];
        if(!$driver){
            $this->error('非司机，不可使用此功能');
        }

        $result = Sms::check($mobile, $captcha, 'changemobile');
        if (! $result) {
            $this->error(__('验证码错误'));
        }

        $driver['mobile']=$mobile;
        $driver->save();

        Sms::flush($mobile, 'changemobile');
        $this->success();
    }
}